package com.example.mypplication.sortlist.newsortlist


import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mypplication.R
import com.example.mypplication.sortlist.newsortlist.SideBar.OnTouchingLetterChangedListener

class ContactListView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    companion object {
        private val allLetters = arrayOf(
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        )
    }

    // 视图组件
    private val recyclerView: RecyclerView
    private val sideBar: SideBar
    private val dialogText: TextView
    private val floatingHeader: LinearLayout
    private val floatingHeaderText: TextView
    private val groupSendBtn: TextView

    // 适配器
    private val adapter: ContactListAdapter
    private var contactList: List<SortModel> = emptyList()

    // 回调接口
    var onItemClickListener: ((SortModel) -> Unit)? = null
    var onGroupSendClickListener: (() -> Unit)? = null

    init {
        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.view_contact_list, this, true)

        // 初始化视图
        recyclerView = findViewById(R.id.contact_recycler_view)
        sideBar = findViewById(R.id.side_bar)
        dialogText = findViewById(R.id.dialog_text)
        floatingHeader = findViewById(R.id.floating_header)
        floatingHeaderText = findViewById(R.id.floating_header_text)
        groupSendBtn = findViewById(R.id.group_send_btn)

        // 设置适配器
        adapter = ContactListAdapter()
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter

        // 设置侧边栏
        sideBar.setTextView(dialogText)
        sideBar.setOnTouchingLetterChangedListener(object : OnTouchingLetterChangedListener {
            override fun onTouchingLetterChanged(s: String) {
                scrollToLetter(s)
            }

        })
//        sideBar.setOnTouchingLetterChangedListener { letter ->
//            scrollToLetter(letter)
//        }

        // 设置群发按钮点击事件
        groupSendBtn.setOnClickListener {
            toggleCheckMode()
            onGroupSendClickListener?.invoke()
        }

        // 设置列表项点击事件
        adapter.onItemClickListener = { contact ->
            if (adapter.isCheckMode) {
                contact.isChecked = !contact.isChecked
                adapter.notifyItemChanged(contactList.indexOf(contact))
            } else {
                onItemClickListener?.invoke(contact)
            }
        }

        // 设置滚动监听
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                updateFloatingHeader()
            }
        })
    }

    /**
     * 设置联系人数据
     */
    fun setContacts(contacts: List<SortModel>) {
        contactList = contacts.sortedWith(PinyinComparator())
        adapter.submitList(contactList)
        updateSideBarLetters()
    }

    private fun updateSideBarLetters() {
        // 获取所有存在的首字母
        val existingLetters = contactList
            .map { it.sortLetters.substring(0, 1).uppercase() }
            .distinct()
            .filter { it in allLetters || it == "#" } // 只保留A-Z和#
            .toTypedArray()

        sideBar.setDisplayLetters(existingLetters)
    }

    /**
     * 滚动到指定字母的位置
     */
    private fun scrollToLetter(letter: String) {
        val position = adapter.getPositionForSection(letter[0].toInt())
        if (position != -1) {
            recyclerView.scrollToPosition(position)
        }
    }

    /**
     * 切换选择模式
     */
    private fun toggleCheckMode() {
        adapter.isCheckMode = !adapter.isCheckMode
    }

    /**
     * 更新悬浮标题
     */
    private fun updateFloatingHeader() {
        val layoutManager = recyclerView.layoutManager as LinearLayoutManager
        val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()

        if (firstVisiblePosition != -1 && firstVisiblePosition < contactList.size) {
            val section = contactList[firstVisiblePosition].sortLetters[0]
            floatingHeaderText.text = section.toString()

            // 处理悬浮标题的动画效果
            val nextSectionPos = adapter.getPositionForSection(section.toInt() + 1)
            if (nextSectionPos == firstVisiblePosition + 1) {
                val firstVisibleView = layoutManager.findViewByPosition(firstVisiblePosition)
                firstVisibleView?.let {
                    val titleHeight = floatingHeader.height
                    val bottom = it.bottom
                    if (bottom < titleHeight) {
                        floatingHeader.translationY = (bottom - titleHeight).toFloat()
                    } else {
                        floatingHeader.translationY = 0f
                    }
                }
            }
        }
    }
}